import { View, Text } from '@tarojs/components';
import { useMemo, useState } from 'react';
import classNames from 'classnames';
import Layout from '../Layout';
import './index.scss';

const BadgeNumber = ({ count, dot, color = '#e87369', text, maxCount = 99, child, outside, layout }) => {
  const style = useMemo(() => {
    if (!color || color === '#e87369') {
      return {};
    }
    return {
      backgroundColor: color,
    };
  }, [color]);

  return (
    <>
      {(!!count || !!text || dot) && (
        <>
          {!dot ? (
            <>
              {((outside && !!layout.width) || !outside) && (
                <View
                  className={classNames(
                    'pd-badge__count',
                    !outside && child && 'pd-badge__count--child',
                    outside && 'pd-badge__count--outside',
                  )}
                  style={{
                    ...style,
                    ...(outside
                      ? {
                          left: layout.width - 4,
                        }
                      : {}),
                  }}>
                  <Text className='pd-badge__count__text'>{text || (count > maxCount ? maxCount + '+' : count)}</Text>
                </View>
              )}
            </>
          ) : (
            <View className={classNames('pd-badge__dot', child && 'pd-badge__dot--child')} style={style} />
          )}
        </>
      )}
    </>
  );
};

export const Badge = ({ count, dot, color, text, maxCount, outside, children, className, ...props }) => {
  const [layout, setLayout] = useState({ width: 0, height: 0 });

  if (children) {
    if (outside) {
      return (
        <Layout className={`pd-badge${className ? ' ' + className : ''}`} {...props} onLayout={setLayout}>
          {children}
          <BadgeNumber count={count} dot={dot} color={color} text={text} maxCount={maxCount} child outside layout={layout} />
        </Layout>
      );
    }
    return (
      <View className={`pd-badge${className ? ' ' + className : ''}`} {...props}>
        {children}
        <BadgeNumber count={count} dot={dot} color={color} text={text} maxCount={maxCount} child />
      </View>
    );
  } else {
    return <BadgeNumber count={count} dot={dot} color={color} text={text} maxCount={maxCount} />;
  }
};
export default Badge;
